<?php
//
//  VictoryCMS - Content managment system and framework.
//  Copyright (C) 2009  Lewis Gunsch
//
//  This file is part of VictoryCMS.
//  
//  VictoryCMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  VictoryCMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with VictoryCMS.  If not, see <http://www.gnu.org/licenses/>.

/**
 * VictoryCMS - EventManager
 * 
 * @license http://www.gnu.org/licenses/gpl.html
 * @author Lewis Gunsch
 * @package Deprecated
 */

/**
 * @deprecated This class will be removed in future versions!
 * 
 * This File include the functions necessary for events management of the
 * Victory church web site.
 * 
 * @package Deprecated
 **/

class EventManager implements DisplayablePage {

	// Event Constants //////////////////////////////////////////////////////////
	const CURRENT_EVENT = "current_event_id";

	// form Post variable constants /////////////////////////////////////////////
	const EVENT = "event";
	const ACTION_BUTTON = "action_button";
	const TITLE = "title";
	const DESCRIPTION = "description";
	const BODY = "body";
	const START = "start";
	const END = "end";


	/**
	 * This function posts a form of buttons for selecting an event.
	 * This requires the client to initialize sessions.
	 * @param action The page this function is used on.
	 * @return The html of the event chooser form
	 **/
	private function postEventChooserForm( $action ) {

		$html = "";

		// Connect and execute query
		$db = VcmsDBFactory::createVcmsDb();
		$query = sprintf( "SELECT event_id, title, start FROM Events" );
		$db->runQuery($query);
		
		// Build initial form
		$html .=  "<form name='event_selector' method='POST' action='". $action ."'>\n";

		// Parse results into form
		$i = 0;
		while( $row = $db->fetchRow() ) {
			$event_data = $row["event_id"] ." ". $row["start"] ."&nbsp;-&nbsp;". $row["title"];
			if ( $_SESSION[self::CURRENT_EVENT] != $row["event_id"] ) {
				$html .=  "<input id='event". $i ."' class='chooser' type='submit' name='". self::EVENT ."'";
				$html .=  " onMouseOver='goLite(\"event".$i."\")' onMouseOut='goDim(\"event".$i."\")'";
				$html .=  " value='". $event_data ."' style='width: 300px;'/><br>\n";
			} else {  // This event has been selected
				$html .=  "<div class='selected' style='width: 300px;'";
				$html .=  " align='center' name='". $row["event_id"] ."'>";
				$html .=  $event_data ."</div>\n";
			}
			$i++;
		}
		$html .=  "</form>\n";

		// Close connection and return
		$db->cleanUp();
		return $html;
	}


	/**
	 * This function posts an event update form for the event id logged in the session.
	 * This function requires the cleint to initialize sessions.
	 * @param action The page this function is used on
	 * @return The html of the event updater form
	 **/
	private function postEventUpdaterForm( $action ) {

		$html = "";

		// Connect to database
		$db = VcmsDBFactory::createVcmsDb();
		
		$select = "SELECT event_id, title, description, start, end, updated, body ";
		$from = "FROM Events, Event_Body ";
		$where = sprintf( "WHERE event_id=%d AND event_body_id=%d", $_SESSION[self::CURRENT_EVENT], $_SESSION[self::CURRENT_EVENT] );
		$query = sprintf( "%s %s %s", $select, $from, $where );
		$db->runQuery($query);
		
		// Build initial form
		$html .=  "<form name='event_updater' method='POST' action='". $action ."'>\n";
		$html .=  "<table name='event_updater_table' border='0'>\n";

		// Parse results into form
		$row = $db->fetchRow();
		
		// id and created table row
		$html .=  "<tr><td style='width: 30%;'>\n<label class='updater' for='event_id_field'>ID:&nbsp;</label>";
		$html .=  "<input class='updater' type='text' name='event_id' id='event_id_field' size='10'";
		$html .=  " readonly value='". $row["event_id"]. "'/>\n</td><td style='width: 70%;'>\n";
		$html .=  "<label class='updater' for='updated_field'>Updated:&nbsp;</label>";
		$html .=  "<input class='updater' type='text' name='updated' id='updated_field' size='16'";
		$html .=  " readonly value='". substr( $row["updated"], 0, 16 ) ."'/>\n</td></tr>";

		// Title table row
		$html .=  "<tr><td colspan='2'>\n<label class='updater' for='title_field'>Title:&nbsp;</label>";
		$html .=  "<input class='updater' type='text' name='". self::TITLE ."' id='title_field' size='45' maxlength='45'";
		$html .=  " value='". $row["title"] ."'/>\n</td></tr>";

		// Description table row
		$html .=  "<tr><td colspan='2'>\n<label class='updater' for='description_field'>Description:&nbsp;</label>";
		$html .=  "<textarea class='updater' name='". self::DESCRIPTION ."' id='description_field' rows='2' cols='45'>";
		$html .=  "". $row["description"] ."</textarea></td></tr>";

		// Body table row
		$html .=  "<tr><td colspan='2'>\n<label class='updater' for='body_field'>Event Info:&nbsp;</label>";
		$html .=  "<textarea class='updater' name='". self::BODY ."' id='body_field' rows='20' cols='45'>";
		$html .=  "". $row["body"] ."</textarea></td></tr>";

		// Start and end table row
		$html .=  "<tr><td style='width: 50%;'>\n<label class='updater' for='start_field'>Start Time:&nbsp;</label>";
		$html .=  "<input class='updater' type='text' name='". self::START ."' id='start_field' size='16'";
		$html .=  " value='". substr( $row["start"], 0, 16 ) ."'/>\n</td><td style='width: 50%;'>\n";
		$html .=  "<label class='updater' for='end_field'>End Time:&nbsp;</label>";
		$html .=  "<input class='updater' type='text' name='". self::END ."' id='end_field' size='16'";
		$html .=  " value='". substr( $row["end"], 0, 16 ) ."'/>\n</td></tr>";

		$html .=  "<tr><td colspan='2' align='center'>\n";

		// Submitt button actions
		if ( $_POST[self::ACTION_BUTTON] == "New" ) {
			$html .=  "<input id='action1' type='submit' name='". self::ACTION_BUTTON ."' value='Insert'";
			$html .=  " onMouseOver='goLite(\"action1\")' onMouseOut='goDim(\"action1\")'";
			$html .=  "class='chooser' style='width: 50px;' />\n";
		} else {
			$html .=  "<input id='action2' type='submit' name='". self::ACTION_BUTTON ."' value='Update'";
			$html .=  " onMouseOver='goLite(\"action2\")' onMouseOut='goDim(\"action2\")'";
			$html .=  " class='chooser' style='width: 50px;' />\n";
			$html .=  "<input id='action3' type='submit' name='". self::ACTION_BUTTON ."' value='New'";
			$html .=  " onMouseOver='goLite(\"action3\")' onMouseOut='goDim(\"action3\")'";
			$html .=  " class='chooser' style='width: 50px;' />\n";
			$html .=  "<input id='action4' type='submit' name='". self::ACTION_BUTTON ."' value='Delete'";
			$html .=  " onMouseOver='goLite(\"action4\")' onMouseOut='goDim(\"action4\")'";
			$html .=  "  onClick='return confirm(\"Delete ?\");' class='chooser' style='width: 50px;' />\n";
		}

		$html .=  "</td></tr>";
		$html .=  "</table></form>\n";

		// Close connection and return
		$db->cleanUp();
		return $html;
	}


	/**
	 * This function handles the actions for the action buttons for the event update form.
	 **/
	private function eventButtonActionHandler() {

		// Connect to database
		//$conn = getConnected();
		$db = VcmsDBFactory::createVcmsDb();
		
		// Set currently selected event
		if (! empty($_POST[self::EVENT]) ) {

			$event_field = $_POST[self::EVENT];
			$event_id; // declare
			sscanf( $event_field, "%d", $event_id );
			$_SESSION[self::CURRENT_EVENT] = $event_id;
			$_SESSION[UPDATE] = false;
			unset( $_POST[self::EVENT] ); // no longer used
			unset( $event_id ); // no longer used
		}

		if ( $_POST[self::ACTION_BUTTON] == "New" ) {

			// post new form
			unset( $_SESSION[self::CURRENT_EVENT] );

		} elseif ( $_POST[self::ACTION_BUTTON] == "Insert" ) {  // Insert new Event

			// Insert main event
			$insert = "INSERT INTO Events (event_id, title, description, start, end, updated)";
			$values = sprintf( "VALUES ( null, '%s', '%s', '%s', '%s', null )",
			$_POST[self::TITLE], $_POST[self::DESCRIPTION], trim( $_POST[self::START] ), trim( $_POST[self::END] ) );
			$query = sprintf( "%s %s", $insert, $values );
			$db->runQuery($query);
			
			$query = sprintf( "SELECT MAX(event_id) FROM Events" ); // assume last event inserted is max
			$db->runQuery($query);
			$row = $db->fetchRow();
			$new_event_id = $row[0];

			// Insert event body
			$query = sprintf( "INSERT INTO Event_Body (event_body_id, body) VALUES (%s, '%s')",
			$new_event_id, $_POST[self::BODY] );
			$db->runQuery($query);
			
			// set current event id to new one
			$_SESSION[self::CURRENT_EVENT] = $new_event_id;

		} elseif ( $_POST[self::ACTION_BUTTON] == "Update" ) {

			// Update Event
			$update = "UPDATE Events, Event_Body";
			$set = sprintf( "SET title='%s', start='%s', end='%s', description='%s', body='%s'",
			$_POST[self::TITLE], trim( $_POST[self::START] ), trim( $_POST[self::END] ),
			$_POST[self::DESCRIPTION], $_POST[self::BODY] );
			$where = sprintf( "WHERE event_id=%d AND event_body_id=%d", $_SESSION[self::CURRENT_EVENT], $_SESSION[self::CURRENT_EVENT] );
			$query = sprintf( "%s %s %s", $update, $set, $where );
			$db->runQuery($query);
			
		} elseif ( $_POST[self::ACTION_BUTTON] == "Delete" ) {

			// Delete Event
			$query = sprintf( "DELETE FROM Events WHERE event_id=%d", $_SESSION[self::CURRENT_EVENT] );
			$db->runQuery($query);
			$query = sprintf( "DELETE FROM Event_Body WHERE event_body_id=%d", $_SESSION[self::CURRENT_EVENT] );
			$db->runQuery($query);
			// reset current event id
			unset( $_SESSION[self::CURRENT_EVENT] );
		}

		// Close connection and return
		$db->cleanUp();
		return;
	}


	/**
	 * This function returns the html content of the page in a string.
	 * The content should not contain the template, just the page container
	 * content.
	 *
	 * @param currentPage The current relative page path calling this function.
	 *
	 * @return A string containing the html page content
	 **/
	public function renderPage( $currentPage ) {
		$html = "";

		$html .=  "<h3 align='center'>Event Viewer-Updater</h3>\n";
		$html .=  "<table class='gray' id='event_chooser_updater' border='1' align='center' cellpadding='3' ";
		$html .=  "cellspacing='0' class='event_update_table'>\n";
		$html .=  "<tr class='gray'><th class='gray' align='center' border='0'>&nbsp;Upcomming Events&nbsp;</th>";
		$html .=  "<th class='gray' align='center' border='0'>&nbsp;View-Update&nbsp;</th></tr>\n";
		$html .=  "<tr class='gray'><td class='gray'>\n";
		$html .= $this->postEventChooserForm( $currentPage );
		$html .=  "</td><td class='gray'>\n";
		$html .= $this->postEventUpdaterForm( $currentPage );
		$html .=  "</td></tr>";
		$html .=  "</table>\n<hr>";

		return $html;
	}


	/**
	 * This method is run before the page is displayed and
	 * before any content is retrieved. This method is meant
	 * to let the page do any necessary preprocessing.
	 *
	 **/
	public function pagePreProcess() {

		// Button action handler
		$this->eventButtonActionHandler();
	}

	/**
	 * This function returns the title of the DisplayablePage
	 * in a string.
	 *
	 * @return The title of the page
	 **/
	public function getTitle() {
		return "Events Manager";
	}

	/**
	 * This function returns the name of the DisplayablePage
	 * in a string.
	 *
	 * @return The name of the page.
	 **/
	public function getName() {
		return "Event Manager";
	}

	/**
	 * This function returns a short text description of a
	 * DisplayablePage in a string.
	 *
	 * @return A short description of the page
	 **/
	public function getDescription() {
		return "create, delete, and update event listings.";
	}

	/**
	 * This function returns a comma seperated list
	 * of describing keywords in a string.
	 *
	 * @return A comma seperated keyword string
	 **/
	public function getKeywords() {
		return "event, calendar";
	}

	/**
	 * This function returns the css style sheet
	 * in a string for the page.
	 *
	 */
	public function getHeaderInfo() {
		$html = "";
		$html .= '<link href="http://www.victoryrock.org/members/vcotr1style.css" rel="stylesheet" type="text/css">';
		$html .= '<script src="http://www.victoryrock.org/members/vcotr1javascript.js" type="text/javascript"></script>';
		return $html;
	}

	/**
	 * This method returns the minimum necessary permissions
	 * needed to be able to view this page.
	 *
	 * @return a permission object with permission set.
	 **/
	public function getPagePermissionLevel() {

		return new Permission("Admin");
	}

}

?>